define( [ 
		'underscore', 
		'jquery',
		'backbone', 
		'view/library',
	  	'jqueryui',	
	], function( _, $, Backbone, LibraryView ) {

	var AppView = Backbone.View.extend({
		el:$("#appview"),

		libraryView: {},

		initialize:function(){
			debugger;
			this.libraryView = new LibraryView();
			this.render();

			this.listenTo( appCTX, 'image:processed', this.processForm );
			// This pattern is binding the events triggered inside appCTX
			//  object into local object 'this'. appCTX is a global context
			//  object. It helps to transmit the messages for callback functions.
		},

		render:function(){
			console.log("AppView render");
			this.libraryView.render();
		},

		processForm: function(formDataStr) {
			var fData = JSON.parse(formDataStr);
			console.log("processForm:" + formDataStr);
			this.libraryView.collection.create(fData);
		},

		addBook:function(e) {
			e.preventDefault();
			var formData = {};
			var f;
//			debugger;
			$("#addBook div").children("input").each(function(i, el){
//				debugger;
				if( el.files && el.files[0] ) {
					f = el.files[0];
					console.log("Processing image");
    				// Only process image files. Image files
					// does not releal the path information, just
					// to content accessible via the FileReader.
    				if (f.type.match('image.*')) {
				   	var reader = new FileReader();
						// Need a closure to capture the file information.
						reader.onload = (function(ctx, theFile) {
      					return function(e) {
								console.log(e.target.result);
								formData.coverImage=e.target.result;
								// trigger even on the context object
								// once the content of the file is loaded
								// into the form structure
								appCTX.trigger('image:processed', JSON.stringify(formData));
      					};
    					})(this, f);

 		  			 	// Trigger the Read operation for the selected image. The callback
						// will get the URL stream, which is base64 coded stream.
    					reader.readAsDataURL(f);
					} else {
						console.error("You have to pick an image file");
					}
				} else {
					if( el.id === "releaseDate" ) {
						// Without jQuery UI, providing just a year in the input field ...
						// formData[el.id] = new Date($(el).val(), 1, 1).getTime()
						formData[el.id] = $("#releaseDate").datepicker("getDate").getTime();
						// if jQueryUI is used ...
					} else {
						formData[el.id] = $(el).val();
					}
				}
			});
			// local model only ...
			// books.push(formData);
			// this.collection.add(new Book(formData));
			
			// serializing to server ...
			// this.collection.create(formData);
		},

		testMessage: function(e) {
			e.preventDefault();
			e.stopPropagation();
			console.log("LibraryApp context");
			console.log(e);
		},

		events:{
			"click #add":"addBook",
			"click #newItem":"testMessage"
		}
	});
	return AppView;
});
